package com.opencvjava.lessons.imgproc;

import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import org.springframework.stereotype.Service;

import static com.opencvjava.support.util.CvUtils.imshow;
import static com.opencvjava.support.util.CvUtils.mat;
import static org.opencv.imgproc.Imgproc.getAffineTransform;
import static org.opencv.imgproc.Imgproc.getRotationMatrix2D;
import static org.opencv.imgproc.Imgproc.warpAffine;

@Service
public class L16_Affine {
    public void test() {
        Mat src = mat("lena.jpg");
        if (src.empty()) {
            throw new RuntimeException("图片读取失败");
        }
        Point[] srcTri = new Point[3];
        srcTri[0] = new Point(0, 0);
        srcTri[1] = new Point(src.cols() - 1, 0);
        srcTri[2] = new Point(0, src.rows() - 1);
        Point[] dstTri = new Point[3];
        dstTri[0] = new Point(0, src.rows() * 0.33);
        dstTri[1] = new Point(src.cols() * 0.85, src.rows() * 0.25);
        dstTri[2] = new Point(src.cols() * 0.15, src.rows() * 0.7);
        Mat warpMat = getAffineTransform(new MatOfPoint2f(srcTri), new MatOfPoint2f(dstTri));
        Mat warpDst = Mat.zeros(src.rows(), src.cols(), src.type());
        warpAffine(src, warpDst, warpMat, warpDst.size());
        Point center = new Point(warpDst.cols() / 2, warpDst.rows() / 2);
        double angle = -50.0;
        double scale = 0.8;
        Mat rotMat = getRotationMatrix2D(center, angle, scale);
        Mat warpRotateDst = new Mat();
        warpAffine(src, warpRotateDst, rotMat, warpDst.size());
        imshow("Source image", src);
        imshow("Warp", warpDst);
        imshow("Warp + Rotate", warpRotateDst);
    }
}
